package com.jie.server.mvc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.common.http.constant.HttpEntityClassNameConstant;
import com.jie.common.http.constant.HttpHeaderLineNameConstant;
import com.jie.common.http.constant.response.ServerResponseStatusConstant;
import com.jie.common.http.entity.response.HttpResponse;
import com.jie.common.util.JsonUtil;
import com.jie.server.core.ServerApplication;
import com.jie.server.core.entity.SessionNode;
import com.jie.server.core.util.NioUtil;
import com.jie.server.mvc.mapper.SingleChatMapper;
import com.jie.server.mvc.mapper.UserMapper;
import com.jie.server.mvc.model.entity.SingleChat;
import com.jie.server.mvc.model.entity.User;
import com.jie.server.mvc.model.vo.SingleChatQueryVo;
import com.jie.server.mvc.model.vo.SingleChatVo;
import com.jie.server.mvc.service.SingleChatService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 单聊表 服务实现类
 * </p>
 *
 * @author XieZhiJie
 * @since 2022-04-24
 */
@Service
public class SingleChatServiceImpl extends ServiceImpl<SingleChatMapper, SingleChat> implements SingleChatService {

    public final SingleChatMapper singleChatMapper;

    public final UserMapper userMapper;

    @Autowired
    public SingleChatServiceImpl(
            SingleChatMapper singleChatMapper,
            UserMapper userMapper
    ) {
        this.singleChatMapper = singleChatMapper;
        this.userMapper = userMapper;
    }

    @Override
    public boolean chat(SingleChat singleChat) {
        // 1.先判断接收方是否存在
        Integer receiverUserId = singleChat.getReceiveUserId();
        if (receiverUserId == null || this.userMapper.selectById(receiverUserId) == null) {
            return false;
        } else if (singleChat.getChatMessage() == null || "".equals(singleChat.getChatMessage().trim())) {
            return false;
        }
        User sendUser = this.userMapper.selectById(singleChat.getSendUserId());
        // 2.插入数据库信息
        singleChat.setId(null);
        singleChat.setSendTime(LocalDateTime.now());
        singleChat.setSendUserIdent(sendUser.getUsername() + "(" + sendUser.getUserAccount() + ")");
        if (this.singleChatMapper.insert(singleChat) <= 0) {
            return false;
        }
        // 3.尝试判断接收方是否在线并转发信息
        SessionNode sessionNode = ServerApplication.SESSION.get(receiverUserId);
        if (sessionNode != null) {
            SingleChatVo singleChatVo = new SingleChatVo();
            BeanUtils.copyProperties(singleChat, singleChatVo);
            singleChatVo.setSendUserId(sendUser.getUserId());
            singleChatVo.setSendUserAccount(sendUser.getUserAccount());
            singleChatVo.setSendUsername(sendUser.getUsername());
            HttpResponse httpResponse = new HttpResponse();
            httpResponse.addOneHeaderLine(HttpHeaderLineNameConstant.SERVER_RESPONSE_STATUS, ServerResponseStatusConstant.CHAT_FROM_ONE_SUCCESS);
            httpResponse.addOneHeaderLine(HttpHeaderLineNameConstant.ENTITY_DATA_CLASS_NAME, HttpEntityClassNameConstant.JSON_STRING_CLASS_NAME);
            httpResponse.setEntity(JsonUtil.toJson(singleChatVo));
            NioUtil.sendMessage(receiverUserId, httpResponse);
        }
        return true;
    }

    @Override
    public Page<SingleChat> records(Integer userId, SingleChatQueryVo singleChatQueryVo) {
        Page<SingleChat> page = new Page<>(singleChatQueryVo.getCurrent(), singleChatQueryVo.getLimit());
        QueryWrapper<SingleChat> singleChatQueryWrapper = new QueryWrapper<>();
        singleChatQueryWrapper.eq("send_user_id", userId);
        singleChatQueryWrapper.eq("receive_user_id", singleChatQueryVo.getTargetUserId());
        singleChatQueryWrapper.or();
        singleChatQueryWrapper.eq("send_user_id", singleChatQueryVo.getTargetUserId());
        singleChatQueryWrapper.eq("receive_user_id", userId);
        return this.singleChatMapper.selectPage(page, singleChatQueryWrapper);
    }

}
